package com.yoo.ons.function.like.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.paging.DataSource
import androidx.paging.PagedList
import androidx.paging.toLiveData
import com.framework.network.remote.ErrorApiException
import com.framework.network.remote.NetworkObserver
import com.framework.network.remote.endRequest
import com.framework.network.remote.error
import com.framework.network.remote.requestObserver
import com.framework.network.remote.startRequest
import com.framework.network.remote.success
import com.yoo.chat.kit.entity.IMParamsEntity
import com.yoo.module_base.utils.log
import com.yoo.ons.base.BaseVMViewModel
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.base.Request
import com.yoo.ons.base.adpater.Cell
import com.yoo.ons.base.adpater.ID_EMPTY
import com.yoo.ons.base.adpater.ID_ERROR
import com.yoo.ons.base.adpater.ID_MORE_LOADING
import com.yoo.ons.base.adpater.ID_NO_MORE
import com.yoo.ons.base.adpater.LoadStatus
import com.yoo.ons.base.adpater.PAGE_INITIAL
import com.yoo.ons.base.adpater.PageDataSource
import com.yoo.ons.base.adpater.add
import com.yoo.ons.base.adpater.addAll
import com.yoo.ons.base.adpater.isRefreshing
import com.yoo.ons.base.adpater.mutablePutAll
import com.yoo.ons.base.adpater.remove
import com.yoo.ons.base.adpater.removeIfExist
import com.yoo.ons.base.adpater.safelySubList
import com.yoo.ons.base.adpater.superProcessCell
import com.yoo.ons.model.TestModel
import com.yoo.ons.model.WlmListModel
import com.yoo.ons.model.WlmSubListModel
import com.yoo.ons.util.runOnUIThread
import com.yoo.ons.util.runOnWorkThread
import kotlin.math.max
import kotlin.math.min

data class LikeListState(
    val page: Int = PAGE_INITIAL,
    val list: List<String> = listOf(),//保存所有的ID
    val data: Map<String, WlmSubListModel> = mapOf(),//数据存储
    val loading: LoadStatus = LoadStatus.IDLE
) {
    companion object {
        const val ID_DAILY_INCOME_LIST = "ID_DAILY_INCOME_LIST"
    }
}

class WhoLikeMeViewModel : BaseVMViewModel() {
    //    private var listener: HttpRequestListener<WlmListModel>? = null
//    fun setListener(listener: HttpRequestListener<WlmListModel>) {
//        this.listener = listener
//    }
    val loading = MutableLiveData<LoadStatus>()
    var indexState = LikeListState()
    var indexDataSource: PageDataSource? = null

    val dataAllList = indexDataSoureFactory()
        .toLiveData(
            pageSize = 20,
            boundaryCallback = object : PagedList.BoundaryCallback<Cell>() {
                override fun onItemAtEndLoaded(itemAtEnd: Cell) {
                    if (ID_MORE_LOADING == itemAtEnd.id) {
                        reqIndexList(false)
                    }
                }
            }
        )

    //请求数据
    fun reqIndexList(initial: Boolean) {
        runOnWorkThread { internalRequestIndexList(initial) }
    }


    private fun internalRequestIndexList(initial: Boolean) {
        //先虚拟请求一波数据
        if (indexState.loading.isRefreshing()) return
        reducing(initial)
        val nextPage = if (initial) PAGE_INITIAL else (indexState.page + 1)
        val listener = object : HttpRequestListener<WlmListModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["page"] = nextPage
            }

            override fun success(t: WlmListModel?) {
            }

        }
        request(listener, request = object : Request {
            override fun request(map: HashMap<String, Any>, requestEndListener: (() -> Unit?)?) {
                apiService?.postWLMList(map)?.requestObserver(
                    NetworkObserver<WlmListModel>().startRequest {
                        listener.startRequest(it)
                    }.success {
                        //返回结果
                        reducingResult(initial, it?.wlmList ?: listOf())
                    }.error {
                        reducingError(initial)
                    }.endRequest {
                        listener.endRequest()
                    }
                )

            }

        })
        //reducingResult(initial, dataList)
    }

    private fun reducingResult(initial: Boolean, data: List<WlmSubListModel>) {

        if (initial) {
            if (data.isNullOrEmpty()) {
                indexState = indexState.copy(
                    page = PAGE_INITIAL,
                    list = listOf(ID_EMPTY),
                    loading = LoadStatus.SUCCESS
                )
            } else {
                //不为空的情况
                val actuallyFetchOver = data.size < 20
                var preList = data.map { it.userCodeFriend }

                preList =
                    if (actuallyFetchOver) preList.add(ID_NO_MORE) else preList.add(ID_MORE_LOADING)

                indexState = indexState.let {
                    it.copy(
                        page = PAGE_INITIAL,
                        list = preList,
                        data = it.data.mutablePutAll(data.map {
                            Pair(
                                it.userCodeFriend,
                                it
                            )
                        }),
                        loading = LoadStatus.SUCCESS
                    )
                }
            }
        } else {
            indexState = if (data.isEmpty()) {
                indexState.let {
                    it.copy(
                        page = PAGE_INITIAL,
                        list = it.list.remove(ID_MORE_LOADING).add(ID_NO_MORE)
                    )
                }
            } else {
                val actuallyFetchOver = data.size < 20

                indexState.let {
                    it.copy(
                        page = it.page + 1,
                        list = it.list.remove(ID_MORE_LOADING).addAll(data.map {
                            it.userCodeFriend.toString()
                        }).let {
                            if (actuallyFetchOver) it.add(ID_NO_MORE) else it.add(ID_MORE_LOADING)
                        },
                        data = it.data.mutablePutAll(
                            data.map {
                                Pair(it.userCodeFriend.toString(), it)
                            }
                        )
                    )
                }
            }
        }
        Log.i("LikeListFragment", "WhoLikeMeViewModel reducingResult $indexState")
        notifyStateInvalidate()
    }

    private fun reducingError(initial: Boolean) {
        indexState = if (initial) {
            indexState.copy(
                list = listOf(ID_ERROR),
                loading = LoadStatus.FAILURE
            )
        } else {
            indexState.let {
                it.copy(
                    list = it.list.add(ID_NO_MORE),
                    loading = LoadStatus.FAILURE
                )
            }
        }
        notifyStateInvalidate()
    }

    private fun reducing(initial: Boolean) {
        if (initial) {
            indexState = indexState.copy(loading = LoadStatus.LOADING)
            loading.postValue(indexState.loading)
        }
    }

    private fun notifyStateInvalidate() {
        indexDataSource?.invalidate()
        if (loading.value != indexState.loading) {
            runOnUIThread {
                loading.value = indexState.loading
            }
        }
    }

    private fun indexDataSoureFactory(): DataSource.Factory<Int, Cell> =
        object : DataSource.Factory<Int, Cell>() {
            override fun create(): DataSource<Int, Cell> {
                return object : PageDataSource() {
                    override fun totalCount(): Int {
                        return indexState.list.size
                    }

                    override fun loadRange(start: Int, count: Int): List<Cell?> {
                        val list = indexState.list
                        return list.safelySubList(max(0, start), min(list.size, start + count))
                            .map {
                                superProcessCell(it)
                                    ?: Cell(
                                        ItemType.LikeListData,
                                        it,
                                        extra = indexState.data[it]
                                    )
                            }
                    }
                }.also {
                    indexDataSource = it
                }
            }
        }

    //移除
    fun removeModel(userCode: String) {
        //删除先去掉的接口，以前的逻辑是先判断你是否是会员
        runOnWorkThread {
            indexState = indexState.let {
                it.copy(list = it.list.removeIfExist {
                    it == userCode
                })
            }
            notifyStateInvalidate()
        }
    }

    fun openChatPage(targetId:String,type:Int){
        val listener = object : HttpRequestListener<IMParamsEntity>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["userCodeFriend"] = targetId
                params["type"] = type
            }

            override fun success(t: IMParamsEntity?) {
            }
        }
        request(listener, request = object : Request {
            override fun request(map: HashMap<String, Any>, requestEndListener: (() -> Unit?)?) {
                apiService?.postOpenChatPage(map)?.requestObserver(
                    NetworkObserver<IMParamsEntity>().startRequest {
                        listener.startRequest(it)
                    }.success {
                        log("WhoLikeMeViewModel openChatPage success")
                    }.error {
                        if (it is ErrorApiException) {
                            log("WhoLikeMeViewModel openChatPage error ${it.code}")
                        }
                    }.endRequest {
                        listener.endRequest()
                    }
                )

            }

        })
    }
    fun sendChatMessage(toUserId: String,callback:()->Unit) {
        val listener = object : HttpRequestListener<String>() {
            override fun addRequestParams(params: HashMap<String, Any>) {
                params["toUserId"] = toUserId
            }

            override fun success(t: String?) {
            }
        }
        request(listener, request = object : Request {
            override fun request(map: HashMap<String, Any>, requestEndListener: (() -> Unit?)?) {
                apiService?.postTryToSend(map)?.requestObserver(
                    NetworkObserver<String>().startRequest {
                        listener.startRequest(it)
                    }.success {
                        log("WhoLikeMeViewModel sendChatMessage success")
                        callback.invoke()
                    }.error {
                        if (it is ErrorApiException) {
                            log("WhoLikeMeViewModel sendChatMessage error ${it.code}")
                        }
                    }.endRequest {
                        listener.endRequest()
                    }
                )

            }

        })
    }

    //wlm页面信息弹窗点击了喜欢和不喜欢
    val likeTypeLiveData = MutableLiveData<Int>()
    fun clickLikeType(type: Int){
        likeTypeLiveData.value = type
    }

}

//class WhoLikeMeViewModelFactory : ViewModelProvider.Factory {
//    override fun <T : ViewModel> create(modelClass: Class<T>): T {
//        if (modelClass.isAssignableFrom(WhoLikeMeViewModel::class.java)) {
//            return WhoLikeMeViewModel() as T
//        }
//        //noinspection unchecked
//        throw IllegalArgumentException("Unknown ViewModel class")
//    }
//}